import React, {useState} from "react";
import parse, {domToReact} from "html-react-parser";
//@ts-ignore
import {Prism as SyntaxHighlighter} from "react-syntax-highlighter";
//@ts-ignore
import {atomDark, dracula, github, okaidia, solarizedlight} from "react-syntax-highlighter/dist/esm/styles/prism";
import styles from './index.less';

function CopyButton({ code }:{code: any}) {
  const [copied, setCopied] = useState(false);

  const copyToClipboard = () => {
    navigator.clipboard.writeText(code).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    });
  };

  return (
    <button
      onClick={copyToClipboard}
      style={{
        position: "absolute",
        right: 10,
        top: 10,
        padding: "2px 8px",
        fontSize: 12,
        cursor: "pointer",
        background: copied ? "#4caf50" : "#ddd",
        border: "none",
        borderRadius: 4,
        color: copied ? "#fff" : "#333",
        userSelect: "none",
        transition: "background-color 0.3s",
        zIndex: 10,
      }}
      aria-label="复制代码"
    >
      {copied ? "复制成功" : "复制"}
    </button>
  );
}

export default function ContentRenderer({ html }:{html: string}) {
  const options = {
    replace: (domNode: any) => {
      if (domNode.name === "img") {
        const attribs = domNode.attribs || {};
        const realSrc = attribs["data-src"] || attribs.src || "";
        delete attribs["width"];
        delete attribs["height"];
        console.log(attribs);
        return (
          <img
            {...attribs}
            src={realSrc}
            alt={attribs.alt || ""}
            decoding={attribs.decoding}
            className={attribs.class}
            loading="lazy"
            style={{ width: "100%" }}
          />
        );
      }

      if (
        domNode.name === "pre" &&
        domNode.children &&
        domNode.children.length === 1 &&
        domNode.children[0].name === "code"
      ) {
        const codeNode = domNode.children[0];
        const className = codeNode.attribs.class || "";
        const languageMatch = className.match(/language-(\w+)/);
        const language = languageMatch ? languageMatch[1] : "";

        const codeContent = domToReact(codeNode.children, options);
        const codeString = Array.isArray(codeContent)
          ? codeContent.map((c) => (typeof c === "string" ? c : "")).join("")
          : codeContent;

        return (
          <div style={{ position: "relative" }}>
            <CopyButton code={codeString} />
            <SyntaxHighlighter
              language={language}
              style={okaidia}
              showLineNumbers
              PreTag="div"
            >
              {codeString}
            </SyntaxHighlighter>
          </div>
        );
      }
      return null;
    },
  };

  return <div className={styles.content}>{parse(html, options)}</div>;
}
